﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using ERDDiagram.CrmSdk;
using System.ServiceModel;

namespace ERDDiagram.helpers
{
    public static class WCFHelper
    {
        /// <summary>
        /// Opens a connection to the CRM Organisation Service
        /// </summary>
        /// <param name="ServerUrl"></param>
        /// <returns></returns>
        public static IOrganizationService GetConnection(Uri ServerUrl)
        {



            Uri   serviceUrl = CombineUrl(ServerUrl, "/XRMServices/2011/Organization.svc/web");
            BasicHttpBinding binding = new BasicHttpBinding((Uri.UriSchemeHttps == serviceUrl.Scheme) ? BasicHttpSecurityMode.Transport : BasicHttpSecurityMode.TransportCredentialOnly);
            binding.MaxReceivedMessageSize = int.MaxValue;
            binding.MaxBufferSize = int.MaxValue;
            binding.SendTimeout = TimeSpan.FromMinutes(2);

            return new CrmSdk.OrganizationServiceClient(binding, new EndpointAddress(serviceUrl));
        }


        /// <summary>
        /// Combines a URI with a relative URI
        /// </summary>
        /// <param name="baseValue">Base (absolute) URI</param>
        /// <param name="value">Relative URI that is to be used</param>
        /// <returns>Combined URI</returns>
        public static Uri CombineUrl(Uri baseValue, string value)
        {
            if (null == baseValue)
            {
                throw new ArgumentNullException("baseValue");
            }
            else if (string.IsNullOrEmpty(value))
            {
                return baseValue;
            }

            //Ensure that a double '/' is not being added
            string newValue = baseValue.AbsoluteUri;
            if (!newValue.EndsWith("/", StringComparison.Ordinal))
            {
                //Check if there is a character at the beginning of value
                if (!value.StartsWith("/", StringComparison.Ordinal))
                {
                    newValue += "/";
                }
            }
            else if (value.StartsWith("/", StringComparison.Ordinal))
            {
                value = value.Substring(1);
            }

            //Create the combined URL
            return new Uri(newValue + value);
        }

    }
}
